package com.tiancheng.onecode.model.thrid;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.tiancheng.onecode.exception.Asserts;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author: kellen
 * @Description: 设备播报
 * @Date: create in 2025/2/27 11:32
 */
@Data
public class DeviceNoticeReq {

    /**
     * 商户id
     */
    @JsonProperty(value = "BusinessUnitID")
    private String businessUnitID;
    /**
     * 内容类型
     * 0：包含金额；1：普通文本
     */
    @JsonProperty(value = "MsgFormatType")
    private String msgFormatType;
    /**
     * 与TemplateMsg不可同时为空
     */
    @JsonProperty(value = "Msg")
    private String msg;
    /**
     * 与Msg不可同时为空
     */
    @JsonProperty(value = "TemplateMsg")
    private String templateMsg;
    /**
     * 消息id
     */
    @JsonProperty(value = "MsgId")
    private String msgId;
    /**
     * 签名
     * <p>
     * //(BusinessUnitID+MsgFormatType+Msg+TemplateMsg+MsgId)==>base64==>md5_32Upper==>md5_32Upper
     */
    @JsonProperty(value = "Sign")
    private String sign;

    public String genSign() {
        if (this.msg == null) {
            this.msg = "";
        }
        if (this.templateMsg == null) {
            this.templateMsg = "";
        }
        // 编码
        String signStr = DatatypeConverter.printBase64Binary((this.businessUnitID + this.msgFormatType + this.msg + this.templateMsg + this.msgId)
                .getBytes(StandardCharsets.UTF_8));
        signStr = DigestUtils.md5DigestAsHex(signStr.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        signStr = DigestUtils.md5DigestAsHex(signStr.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        return signStr;
    }

    /**
     * 签名校验
     *
     * @param sign
     * @return
     */
    public Boolean checkSign(String sign) {
        if (StringUtils.isEmpty(sign) || StringUtils.isEmpty(this.sign)) {
            return false;
        }
        return this.sign.equals(sign);
    }
}
